<template>
  <el-form
    ref="ruleFormRef"
    :model="passForm"
    status-icon
    :rules="rules"
    label-width="auto"
    label-position="left"
    class="demo-ruleForm"
  >
    <el-form-item label="旧密码" prop="oldPassword">
      <el-input v-model="passForm.oldPassword" type="password" autocomplete="off" show-password/>
    </el-form-item>

    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model="passForm.newPassword" type="password" autocomplete="off" show-password/>
    </el-form-item>
    <el-form-item label="再次确认" prop="confirmPassword">
      <el-input v-model="passForm.confirmPassword" type="password" autocomplete="off" show-password/>
    </el-form-item>
    <div style="padding-top: 50px">
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          保存
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue'
import {ElMessage, FormInstance, FormRules} from 'element-plus'
import {updatePassword} from "@/api/user";
import {UserPasswordForm} from "@/api/user/types";

defineOptions({
  name: "ResetPwd",
  inheritAttrs: false,
});

const ruleFormRef = ref<FormInstance>()

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (value.length < 6) {
      callback(new Error('密码长度不能小于6位'))
    }
    if (passForm.confirmPassword !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('confirmPassword', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能小于6位'))
  } else if (value !== passForm.newPassword) {
    callback(new Error("两次输入不一致!"))
  } else {
    callback()
  }
}
// UserPasswordForm
const passForm = reactive<UserPasswordForm>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

const rules = reactive<FormRules<typeof passForm>>({
  oldPassword: [{validator: validatePass, trigger: 'blur'}],
  newPassword: [{validator: validatePass, trigger: 'blur'}],
  confirmPassword: [{validator: validatePass2, trigger: 'blur'}],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
      updatePassword(passForm).then(() => {
        console.log('updatePassword success!')
        formEl.resetFields()
        ElMessage.success('密码修改成功');
      })
    } else {
      console.log('error submit!')
      ElMessage.success('密码修改失败');
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
